package com.arron.algorithm.leetcodetop100.滑动窗口;

import java.util.HashMap;
import java.util.Map;

/**
 *  最小覆盖子串
 */
public class 最小覆盖字串 {


    public String minWindow(String s, String t) {

        //两个hashmap
        Map<Character,Integer> window = new HashMap<>();
        Map<Character,Integer> need = new HashMap<>();

        for (char c : t.toCharArray()) {
            need.put(c,need.getOrDefault(c,0)+1);
        }

        int l = 0,r = 0;
        int valid = 0;
        int len = Integer.MAX_VALUE;
        int start = 0;
        while (r < s.length()){

            char c = s.charAt(r);
            r++;

            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if (window.get(c).equals(need.get(c))){
                    valid++;
                }
            }

            while (valid == need.size()){
                if (r-l < len){
                    start = l;
                    len = r-l;
                }

                //更新valid值
                if (need.containsKey(s.charAt(l))){
                    if (window.get(s.charAt(l)).equals(need.get(s.charAt(l)))){
                        valid--;
                    }
                    window.put(s.charAt(l),window.get(s.charAt(l))-1);
                }

                //左指针移动
                l++;
            }
        }

        return len == Integer.MAX_VALUE ?
                "" : s.substring(start, start + len);
    }


    public static void main(String[] args) {



    }

}
